// 一.
function p() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            var a = 'hello';
            resolve(a);
        }, 10)
    })
};

function p2(val) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            var b = 'lagou';
            resolve(val + b);
        }, 10)
    })
};

function p3(val) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            var c = 'I ❤ U';
            resolve(val + c);
        }, 10)
    })
};

p().then(p2).then(p3).then(val => {
    console.log(val);
})

// 二
const cars = [{
    name: 'Tom One',
    horsepower: 1,
    dollar_value: 10,
    in_stock: true
},
{
    name: 'Tom Two',
    horsepower: 2,
    dollar_value: 20,
    in_stock: true
},
{
    name: 'Tom Three',
    horsepower: 3,
    dollar_value: 30,
    in_stock: false
}]

const fp = require('lodash/fp');
// 二 - 1
function isLaseInStock (data) {
    return fp.prop('in_stock', data);
}

function lastCar (cars) {
    return fp.last(cars);
}

let lastInStock = fp.flowRight(isLaseInStock, lastCar);
console.log(lastInStock(cars));

// 二 - 2

function isFirstName (data) {
    return fp.prop('name', data);
};

function firstCar (cars) {
    return fp.first(cars);
};

let firstName = fp.flowRight(isFirstName, firstCar);
console.log(firstName(cars));

// 二 - 3
let _average = function (xs) {
    return fp.reduce(fp.add, 0, xs) / xs.length;
};

let averageDollarValue = function (dollar_values) {
    return _average(dollar_values);
};

let dollar_values = function (cars) {
    return fp.map(function (car) {
        return car.dollar_value;
    }, cars);
};

let result = fp.flowRight(averageDollarValue, dollar_values)
console.log(result(cars));

// 二 - 4
const strArr = ['Hello Word'];
let _underscore = fp.replace(/\s+/g, '_');

let sanitizeNames = fp.flowRight(fp.map(fp.flowRight( _underscore, fp.toLower)));
console.log(sanitizeNames(strArr))

// 三
const {Maybe, Container} = require('./support');
let maybe = Maybe.of([5, 6, 1]);

// 三 -1
let ex1 = fp.map(fp.add(1));
maybe = maybe.map(ex1).map(ex1);
console.log(maybe);

// 三 - 2
let xs = Container.of(['aa', 'bb', 'cc'])

let ex2 = () => xs.map(fp.first);
console.log(ex2()._value)

// 三 - 3
let safeProp = fp.curry(function (x, o) {
    return Maybe.of(o[x])
});

let user = {id: 2, name: 'Albert'};

let ex3 = () =>  safeProp('name')(user).map(fp.flowRight(fp.first, fp.split('')));
console.log(ex3()._value);

// 三 - 4
let ex4 = (n) => Maybe.of(n).map(x => parseInt(x));
console.log(ex4('2.1')._value);